package com.month.security.service.ipml;

import com.month.security.dto.response.LoginUser;
import com.month.security.dto.response.Result;
import com.month.security.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 登录校验方法
 */
@Component
@Slf4j
public class LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;



    @Autowired
    private JwtService jwtService;


    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;

        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);
            // 调用AuthenticationManager的authenticate方法进行用户认证
            authentication = authenticationManager.authenticate(authenticationToken);

        } catch (Exception e) {
            if (e instanceof BadCredentialsException){
                throw new BadCredentialsException("密码错误");
            }else {
                throw new RuntimeException(e);
            }
        }
        LoginUser principal = (LoginUser)authentication.getPrincipal();
        log.info("登录用户：{}", principal);
        return jwtService.createToken(principal);
    }

}
